<template>
    <el-row :gutter="20">
        <el-col :span="5">
            <FixedHeightVue>
                <StudentList v-model:student="student" />
            </FixedHeightVue>
        </el-col>
        <el-col :span="19">
            <FixedHeightVue>
                <div class="chat_box" v-if="jedget">
                    <!-- 聊天展示框 -->
                    <div class="chat">
                        <el-scrollbar height="657px" ref="scrollbar">
                            <!-- 聊天内容 -->
                            <div class="chat_content" ref="chatRef" v-for="item in chatList.charRecDtoList"
                                :key="item.id">
                                <!-- 自己 -->
                                <div class="myself" v-if="item.sendUserId == userId">
                                    <!-- 头像 -->
                                    <div class="avatar">
                                        <!-- 内容 -->
                                        <div class="content">
                                            <p style="text-align: right">{{ item.message }}</p>
                                        </div>
                                        <img src="@/assets/userInfo.png" alt="" v-if="!chatList.receiveUserPic" />

                                        <img :src="chatList.receiveUserPic" alt="" v-else />
                                    </div>
                                </div>
                                <!-- 别人 -->
                                <div class="older" v-else>
                                    <!-- 头像 -->
                                    <div class="avatar">
                                        <img src="@/assets/userInfo.png" alt="" v-if="!chatList.sendPic" />
                                        <img :src="chatList.sendPic" alt="" v-else />
                                        <!-- 内容 -->
                                        <div class="content">
                                            <p>{{ item.message }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-scrollbar>
                    </div>
                    <div class="chat_input">
                        <!-- 聊天输入框 -->
                        <input type="text" placeholder="请输入" v-model="msg" />
                        <el-button type="primary" @click="onSendMsg">发送</el-button>
                    </div>
                </div>
                <div v-else>
                    <!-- 没选择学生 -->
                    <MyError title="请选中右边需要聊天的学生"></MyError>
                </div>
            </FixedHeightVue>
        </el-col>
    </el-row>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount, nextTick } from "vue"
import MyError from "@/views/MyError.vue";

import { getChatListApi, sendMessageApi, } from "@/api/index";
import FixedHeightVue from "@/components/base/FixedHeight.vue";
import StudentList from '@/views/teacher/mycourse/components/StudentList'

import useUserInfo from "store/useUserInfo.js";
const useUserInfoStore = useUserInfo();
import { storeToRefs } from 'pinia'
const { userInfo } = storeToRefs(useUserInfoStore)
import { ElMessage } from "element-plus";
// 聊天的信息
const chatList = ref({});
const msg = ref("");
// 选中的学生
const student = ref({});
const scrollbar = ref(null)
const chatRef = ref(null)
const jedget = computed(() => {
    const bool = Object.keys(student.value).length > 0;
    if (bool) {
        // 调用获取数据
        // getChatList();
        const sid = student.value.id;
        const uid = userInfo.value.userId

        let wid = null
        if (parseInt(sid) > parseInt(uid)) {
            wid = `${uid}${sid}_${uid}`
        } else {
            wid = `${sid}${uid}_${uid}`
        }
        // 关闭当前连接
        socket.value && socket.value.close();
        initWebsocket(wid);
    }
    return bool;
})
const userId = computed(() => {
    return userInfo.value.userId;
})

// 发送消息
const onSendMsg = () => {
    if (msg.value) {
        sendMessageApi({
            sendUserId: userInfo.value.userId,
            receiveUserId: student.value.id,
            message: msg.value
        }).then(res => {
            if (res.code === "10000") {
                msg.value = "";
                getChatList();
            }
        })
    } else {
        ElMessage.error("发送的消息不能为空！");
    }
}

// 获取聊天列表
const getChatList = () => {
    getChatListApi({
        sendUserId: userInfo.value.userId,
        receiveUserId: student.value.id
    }).then(res => {
        if (res.code == "10000") {
            chatList.value = res.data;
            nextTick(() => {
                console.log('chatRef.value.scrollHeight;', chatRef.value[chatRef.value.length - 1]);
                chatRef.value[chatRef.value.length - 1].scrollIntoView({
                    behavior: 'smooth',
                    block: 'start',
                    inline: 'end',
                });
            })
        }
    })
}


// 初始化websocket
// 存放心跳定时器
const heartBeatTimer = ref(null);
// 存放错误心跳定时器
const heartBeatErrorTimer = ref(null);
// 心跳重新连接
const heartRestartTimer = ref(null);
const socket = ref(null);
const initWebsocket = (id) => {
    if (!window.WebSocket) {
        alert("您的浏览器不支持WebSocket");
    } else {
        // 获取ip地址或者域名
        const ip = location.hostname;
        const wsIP = "ws://" + ip + ":8080";
        // socket.value = new WebSocket(wsIP); // 替换为你的 WebSocket 服务器地址
        socket.value = new WebSocket("ws://124.71.47.110:8089/websocket/" + id); // 替换为你的 WebSocket 服务器地址

        socket.value.onopen = () => {
            console.log("WebSocket 连接已建立");
            getChatList();
            // 开启心跳
            // heartBeat();
        };
        socket.value.onmessage = (event) => {
            heartRestartTimer.value && clearTimeout(heartRestartTimer.value);
            console.log("收到消息:", event.data);
            // const jsonData = JSON.parse(event.data);

            getChatList();

        };

        socket.value.onclose = () => {
            console.log("WebSocket 连接已关闭");

            // reconnect();
            // 在连接关闭后，可以执行清理操作或重新连接等处理
        };
    }
    // 不支持心跳
    const reconnect = () => {
        // 关闭当前连接
        socket.value.close();
        // 等待1s后重新连接
        heartBeatErrorTimer.value = setTimeout(() => {
            initWebsocket();
        }, 1000);
    };
};

onBeforeUnmount(() => {
    // 关闭当前连接
    socket.value && socket.value.close();
    heartBeatTimer.value && clearInterval(heartBeatTimer.value);
    heartRestartTimer.value && clearTimeout(heartRestartTimer.value);
});
onMounted(() => {

})

</script>

<style lang="scss" scoped>
.chat_box {
    height: 100%;
    background-color: #fff;

    .chat {
        height: calc(100% - 30px - 20px);
        border: 1px solid #ccc;
        border-radius: 10px;
        padding: 20px;

        .chat_content {
            .myself {
                margin: 10px 0;

                .avatar {
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;

                    img {
                        width: 40px;
                        height: 40px;
                        border-radius: 50%;
                    }

                    .content {
                        margin-right: 10px;
                    }
                }
            }

            .older {
                margin: 10px 0;

                .avatar {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;

                    img {
                        width: 40px;
                        height: 40px;
                        border-radius: 50%;
                    }

                    .content {
                        margin-left: 10px;
                    }
                }
            }
        }
    }

    .chat_input {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;

        input {
            flex: 1;
            height: 30px;
            /* border-radius: 15px; */
            border: 1px solid #ccc;
            padding: 0 10px;
            margin-right: 10px;
        }
    }
}
</style>